﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.UI.WebControls;
using TSHAK.Components;
using IndoTradingLib.Utils;
using IndoTradingLib.Data;
using IndoTradingLib;
using System.Web;
using System.Text.RegularExpressions;

using System.Web.UI;
using System.Data;
using System.IO;
namespace IndoTradingMemberV2
{
    public partial class product_new2 : ProtectedPage
    {
        protected string sProdID = "";
        protected int sPriceID ;
        protected string sIsTemp = "";
        protected string sQuery = "";
        protected string sCompanyID = "";
        protected CompanyProductCatalogService oProdService;
        protected CompanyService oCompService;
        protected SecureQueryString sq;
        protected SecureQueryString sq2;
        protected ProductImageService oProdImageService;
        protected CountryService oCountryService;
        protected CompanyProductCatalog oProd = null;
        protected string sEncProdID = "";
        
        List<CompanyProductImages> arrImages;


        protected void Page_Load(object sender, EventArgs e)
        {
           
            sq = new SecureQueryString(Request.QueryString["q"]);
            sProdID = sq["ProdID"].ToString();
            sEncProdID = Crypto.EncryptStringAES(sProdID, "indotrade");
            sCompanyID = Cookie.CompanyID;

            oProdService = new CompanyProductCatalogService(this.oContext);
            oProd = oProdService.GetProductByID(sProdID);
            if (oProd == null || oProd.CompanyID.ToLower() != sCompanyID.ToLower())
            {
                Response.Redirect("/product/productcatalog.aspx");
            }

            sq2 = new SecureQueryString();
            sq2["CompanyID"] = Cookie.CompanyID;
            sq2["ProdId"] = sProdID;
            sQuery = sq2.ToString();

            ltrChangeCategory.Text = string.Format("<a href='new.aspx?q={0}'>[{1}]</a>", sq2.ToString(), Resources.Language.ChangeCategory);


            oCompService = new CompanyService(this.oContext);
            oCountryService = new CountryService(this.oContext);
            //btnUpload.OnClientClick = "return btnUpload_Click(" + oProd.StatusID + ")";

            if (oProd != null && oProd.StatusID == EnumStatus.Active.GetHashCode())
            {
                btnNext.OnClientClick = "return btnNext2_Click();";
            }
            if (oProd != null && sq["SetMain"] != null)
            {

                arrImages = oProd.CompanyProductImages.ToList();
                foreach (CompanyProductImages oItem in arrImages)
                {
                    oItem.IsUtama = false;
                }
                oProdImageService = new ProductImageService(oContext);
                CompanyProductImages oImage = oProdImageService.GetCompanyProductImagesById(Convert.ToInt32(sq["SetMain"].ToString()));
                oImage.IsUtama = true;
                oContext.SaveChanges();

            }
            if (ddlCurrency.Items.Count == 0)
            {
                if (oComp.IsExportCompany != null && oComp.IsExportCompany)
                {
                    ddlCurrency.Items.Add(new ListItem("USD", "USD"));
                }
                else
                {
                    ddlCurrency.Items.Add(new ListItem("IDR", "IDR"));
                    ddlCurrency.Items.Add(new ListItem("USD", "USD"));
                }
            }
            if (!IsPostBack)
            {
                BindData();
	            BindPrices();
                BindPictures();
            }
            else
            {
                BindDropDown();
            }
        }
        private void BindDropDown()
        {
            ddlGroupProduct.ClearSelection();
            ddlGroupParent.ClearSelection();
            List<CompanyProductGroup> arrProdGroup = oComp.CompanyProductGroup.ToList();
            
            var parGroup = arrProdGroup.Where(c => !c.ParentID.HasValue);
            if (parGroup.Any())
            {
                //parentSpan.Visible = true;
                ddlGroupParent.DataSource = parGroup;
                ddlGroupParent.DataTextField = "ProductGroupName";
                ddlGroupParent.DataValueField = "ID";
                ddlGroupParent.DataBind();
                
                ddlGroupParent.Items.Insert(0, new ListItem(Resources.Language.ChooseGroupProduct, ""));
                if (oProd.GroupID != null && oProd.CompanyProductGroup != null && oProd.CompanyProductGroup.CompanyProductGroup2 != null)
                    ddlGroupParent.SelectedValue = oProd.CompanyProductGroup.ParentID.ToString();
				else if (parGroup.Any(x => x.ID == oProd.GroupID))
                    ddlGroupParent.SelectedValue = oProd.GroupID.ToString();
            }
            //else
            //{
            //    parentSpan.Visible = false;
            //}

            var dGroup = arrProdGroup.Where(c => c.ParentID.HasValue);
            ddlGroupProduct.DataSource = dGroup;
            ddlGroupProduct.DataTextField = "ProductGroupName";
            ddlGroupProduct.DataValueField = "ID";
            ddlGroupProduct.DataBind();
            ddlGroupProduct.Items.Insert(0, new ListItem(Resources.Language.ChooseGroupProduct, ""));
			if (dGroup.Any(x => x.ID == oProd.GroupID))
            ddlGroupProduct.SelectedValue = oProd.GroupID.ToString();

            for (var i = 1; i < dGroup.Count() + 1; i++)
            {
                ddlGroupProduct.Items[i].Attributes.Add("class", "sub_" + (dGroup.ElementAt(i - 1).ParentID == null ? "" : dGroup.ElementAt(i - 1).ParentID.ToString()));
            }


            if (Request.Form[ddlGroupParent.UniqueID] != null)
            {
                ddlGroupParent.ClearSelection();
                for (int i = 0; i < ddlGroupParent.Items.Count; i++)
                {
                    if (ddlGroupParent.Items[i].Value.Trim() == Request.Form[ddlGroupParent.UniqueID].Trim())
                    {
                        ddlGroupParent.Items[i].Selected = true;
                        break;
                    }
                }
                
            }
            if (Request.Form[ddlGroupProduct.UniqueID] != null)
            {
                ddlGroupProduct.ClearSelection();
                for (int i = 0; i < ddlGroupProduct.Items.Count; i++)
                {
                    if (ddlGroupProduct.Items[i].Value.Trim() == Request.Form[ddlGroupProduct.UniqueID].Trim())
                    {
                        ddlGroupProduct.Items[i].Selected = true;
                        break;
                    }
                }
            }
            

        }
        protected void rptImage_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName != "Delete") return;
            oProdService.DeleteProductImages(sProdID, Convert.ToInt32(e.CommandArgument));
            BindPictures();
        }
        private void BindPictures()
        {
            /*
            DataTable dt = new DataTable();
            dt.Columns.Add("ImageFullPath");
            dt.Columns.Add("Id");
            dt.Columns.Add("IsUtama");
            arrImages = oProd.CompanyProductImages.ToList();
            foreach (CompanyProductImages oImage in arrImages)
            {
                DataRow dr = dt.NewRow();
                dr["ImageFullPath"] = Helper.GetProductImagesURL((int)oProd.Company.ImageServerID, sProdID, sCompanyID, oImage.ImagesName, EnumPictureSize.Thumbnail100).Trim();
                dr["Id"] = oImage.Id;
                dr["IsUtama"] = oImage.IsUtama;
                dt.Rows.Add(dr);
            }
            if (arrImages.Count > 0)
            {
               
                rptImage.DataSource = dt;
                rptImage.DataBind();

            }
            else
            {
               
            }
             */
        }
        private void BindData()
        {
            //Company oComp = oProd.Company;
            //Bind SellingType

            if (oProdService.GetWholeSalePrice(oProd.Id).Count > 0)
            {
                ddlSellingType.ClearSelection();
                ddlSellingType.Items[1].Selected = true;
                ctrlWholeSale.Attributes.Clear();
                

            }
            else
            {
                ddlSellingType.ClearSelection();
                ddlSellingType.Items[2].Selected = true;
            }


            BindDropDown();
            hfGroupProduct.Value = oProd.GroupID.ToString().Trim();
            for (int i = 0; i < ddlGroupProduct.Items.Count; i++)
            {
                if (ddlGroupProduct.Items[i].Value.Trim() != oProd.GroupID.ToString().Trim()) continue;
                ddlGroupProduct.Items[i].Selected = true;
                break;
            }
            if (!String.IsNullOrEmpty(oProd.Currency))
            {
                for (int i = 0; i < ddlCurrency.Items.Count; i++)
                {
                    if (ddlCurrency.Items[i].Value.Trim() == oProd.Currency.Trim())
                    {
                        ddlCurrency.Items[i].Selected = true;
                        break;
                    }
                }
            }

            //Insert Country
            List<Country> arrCountry = oCountryService.GetAllCountry(true);
            ddlCountry.DataSource = arrCountry;
            ddlCountry.DataTextField = "CountryName";
            ddlCountry.DataValueField = "ID";
            ddlCountry.DataBind();
            ddlCountry.Items.Insert(0, new ListItem(Resources.Language.ChooseCountry, ""));
            for (int i = 0; i < ddlCountry.Items.Count; i++)
            {
                if (ddlCountry.Items[i].Value.Trim() == oProd.CountryOrigin.ToString().Trim())
                {
                    ddlCountry.Items[i].Selected = true;
                    break;
                }
            }

            //Insert Product Origin Country
            /*
            List<Country> arrCountry2 = oCountryService.GetAllCountry(true);
            ddlCountryProduct.DataSource = arrCountry2;
            ddlCountryProduct.DataTextField = "CountryName";
            ddlCountryProduct.DataValueField = "ID";
            ddlCountryProduct.DataBind();
            ddlCountryProduct.Items.Insert(0, new ListItem(Resources.Language.ChooseCountry, ""));
            for (int i = 0; i < ddlCountry.Items.Count; i++)
            {
                if (oProd.ProductOriginCountry != null)
                {
                    if (ddlCountryProduct.Items[i].Value.Trim() == oProd.ProductOriginCountry.ToString().Trim())
                    {
                        ddlCountryProduct.Items[i].Selected = true;
                        break;
                    }
                }
            }
            */
            txtNama.Text = oProd.Name;
	        if (oProd.BrandId != null) txtBrand.Text = new BrandService(oContext)[(int) oProd.BrandId].BrandName;
	        txtSku.Text = oProd.Sku;
            txtNamaEng.Text = oProd.NameEng;
            txtUnitPrice.Text = oProd.UnitPrice;
            txtPrice.Text = oProd.Price.ToString();
            txtUnitPrice.Text = oProd.UnitPrice;
			txtWeight.Text = oProd.Weight.ToString("N4", CultureInfo.CurrentCulture);
            txtMOQ.Text = oProd.MOQ.ToString();


            txtDetilEng1.InnerText = oProd.DescriptionEng;
            txtDetilIndo1.InnerText = oProd.Description;

            txtOtherName.Text = oProd.ProductTag;

            if (txtDetilEng1.InnerText == "")
            {
                txtDetilEng1.InnerHtml = "Fill Product Description as complete and detail as possible. Product that has complete information will generate more leads and enquiries to your company and in return will increase your company's sales.<br><br> You can also insert product photos in this description by clicking Insert Photo on the left side<br><br>For translation you can click Link 'Translation Help' on the left side";
            }
            if (txtDetilIndo1.InnerText == "")
            {
                txtDetilIndo1.InnerHtml = "Isi Deskripsi Produk anda dengan Jelas dan Lengkap. Deskripsi Produk yang jelas dan Lengkap akan membuat permintaan Beli terhadap produk ini lebih meningkat , mengurangi pertanyaan kepada anda dan akan membantu omset perusahaan anda meningkat<br><Br>Anda juga bisa menambahkan foto ke dalam deskripsi ini dengan tombol Sisipkan Gambar disamping kiri ini. <br><br> Untuk bantuan terjemahan anda bisa mengklik link 'Bantuan Terjemahan' disamping kiri";
            }

        }

	    protected void BindPrices()
	    {
			lvGrosir.DataSource = oProdService.GetWholeSalePrice(oProd.Id).Select(x => new { UnitPrice=(int)x.Price, x.minQty, ID = generateID(x.ID)});
			lvGrosir.DataBind();
	    }

	    private string generateID(int ID)
	    {
			var sq = new SecureQueryString();
			sq["PriceID"] = ID.ToString();
		    return sq.ToString();
	    }
		
		protected string ReturnMainString(bool IsUtama, string Id)
        {

            if (IsUtama)
            {
                return "[" + Resources.Language.Main + "]";
            }
            sq = new SecureQueryString();
            sq["ProdId"] = sProdID;
            sq["SetMain"] = Id;

            return "<a href='/product/new2.aspx?q=" + sq.ToString() + "'>" + Resources.Language.SetToMain + "</a>";
        }

        protected void btnNext_Click(object sender, EventArgs e)
        {

            int groupId = 0;
            if (!int.TryParse(ddlGroupParent.SelectedValue, out groupId))
            {
                ltrFancyBox.Text = "";
                this.Message = MessageBox.DisplayErrorMessage(Resources.Language.ReqGroupProduct);
	            return;
            }

	        int MOQ;
	        if (!int.TryParse(txtMOQ.Text, out MOQ) || MOQ<=0)
	        {
				this.Message = MessageBox.DisplayErrorMessage(Helper.GetCurrentCulture() == "id-ID"?"Please Fill Minimum Order with positive value":"Mohon Isi Minimum Order dengan bilangan positif");
	            return;
	        }

            
            bool detIndo = true, detEng = true;
            if (txtDetilIndo1.Value.IndexOf("Isi Deskripsi Produk anda") >= 0) detIndo = false;
            if (txtDetilEng1.Value.IndexOf("Fill Product Description") >= 0) detEng = false;


			
			if (!detIndo || !detEng)
            {
                ltrFancyBox.Text = "";
                this.Message = MessageBox.DisplayErrorMessage(Resources.Language.ErrorDescription);
            }
            else if (!Page.IsValid)
            {
                this.Message = MessageBox.DisplayErrorMessage(Resources.Language.ErrorInFields);
            }
            else if (Page.IsValid)
            {
                ltrFancyBox.Text = "";

                //string lang = System.Threading.Thread.CurrentThread.CurrentCulture.Name;
                CompanyProductCatalog oCatalog = oProdService.GetProductByID(sProdID);
                if (oComp.IsGoldMember != null && oComp.IsGoldMember)
                {
                    oCatalog.Name = txtNama.Text;
                    oCatalog.NameEng = txtNamaEng.Text;
                }
                else
                {
                    oCatalog.Name = Helper.ToTitleCase(txtNama.Text);
                    oCatalog.NameEng = Helper.ToTitleCase(txtNamaEng.Text);
                }
                oCatalog.ProductTag = txtOtherName.Text;
                oCatalog.UnitPrice = txtUnitPrice.Text;
                if (txtWeight.Text.Length > 0)
                {
                    if (Helper.GetCurrentCulture() == "id-ID")
                    {
                        if (kilogram.Selected)
                        {
                            oCatalog.Weight = Convert.ToDecimal(txtWeight.Text.Replace(".", ",")) * 1000;
                        }
                        else
                        {
                            oCatalog.Weight = Convert.ToDecimal(txtWeight.Text.Replace(".", ","));
                        }
                    }
                    else
                    {
                        if (kilogram.Selected)
                        {
                            oCatalog.Weight = Convert.ToDecimal(txtWeight.Text) * 1000;
                        }
                        else
                        {
                            oCatalog.Weight = Convert.ToDecimal(txtWeight.Text);
                        }
                    }
                }
				//if (txtMOQ.Text.Length > 0)
				//{
					oCatalog.MOQ = MOQ;
				//}
                if (!string.IsNullOrWhiteSpace(txtBrand.Text))
                    oCatalog.BrandId = new BrandService(oContext).getBrandIdByName(txtBrand.Text);
                else
                    oCatalog.BrandId = null;

                try
                {

                    if (Helper.GetCurrentCulture() == "id-ID")
                    {
                        oCatalog.Price = txtPrice.Text.Length > 0 ? Convert.ToDecimal(txtPrice.Text.Replace(".", ",")) : 0;
                    }
                    else
                    {
                        oCatalog.Price = txtPrice.Text.Length > 0 ? Convert.ToDecimal(txtPrice.Text) : 0;
                    }
                }
                catch (OverflowException)
                {
                    if (System.Threading.Thread.CurrentThread.CurrentCulture.Name == "id-ID")
                        this.Message = MessageBox.DisplayErrorMessage("Harga harus diisi dengan nilai antara " + Decimal.MinValue.ToString().Replace(",", ".") + " hingga " + Decimal.MaxValue.ToString().Replace(",", "."));
                    else
                        this.Message = MessageBox.DisplayErrorMessage("Price value should be between " + Decimal.MinValue + " and " + Decimal.MaxValue);
                    return;
                }

                oCatalog.Sku = txtSku.Text.Trim();
                oCatalog.TemplateID = 2;
                //oCatalog.UpdatedDate = DateTime.Now.ToUniversalTime().AddHours(7);
                oCatalog.CountryOrigin = ddlCountry.SelectedItem.Value.Length > 0 ? Convert.ToInt32(ddlCountry.SelectedItem.Value) : 0;
                /*oCatalog.ProductOriginCountry = ddlCountryProduct.SelectedItem.Value.Length > 0 ? Convert.ToInt32(ddlCountryProduct.SelectedItem.Value) : 0;*/
                oCatalog.Currency = ddlCurrency.SelectedItem.Value;
                oCatalog.Description = Server.HtmlDecode(txtDetilIndo1.InnerText);
                oCatalog.DescriptionEng = Server.HtmlDecode(txtDetilEng1.InnerText);
                oCatalog.LastUpdateBy = null;
                oCatalog.IsExport = this.oComp.IsExportCompany;

                //groupId = 0;
                int.TryParse(hfGroupProduct.Value, out groupId);
                if (groupId > 0)
                {
                    oCatalog.GroupID = groupId;
                }
                else if (int.TryParse(ddlGroupParent.SelectedValue, out groupId))
                {
                    oCatalog.GroupID = groupId;
                }


                oComp = oCatalog.Company;
                try
                {
                    if (oCatalog.Company.IsVerifiedCompany)
                    {
                        if (!String.IsNullOrEmpty(oComp.IsVerifiedCompany.ToString()) && ((bool)oComp.IsVerifiedCompany))
                        {
                            oCatalog.StatusID = (int)EnumStatus.Active;
                            if (oComp.StatusID == (int)EnumStatus.Tester)
                            {
                                oCatalog.StatusID = (int)EnumStatus.Tester;
                            }
                        }
                        else
                        {
                            oCatalog.StatusID = (int)EnumStatus.Pending;
                        }
                    }
                    else
                    {
                        oCatalog.StatusID = (int)EnumStatus.Pending;
                        if (oComp.StatusID == (int)EnumStatus.Tester)
                        {
                            oCatalog.StatusID = (int)EnumStatus.Tester;
                        }
                    }
                }
                catch { oCatalog.StatusID = (int)EnumStatus.Pending; }

                var updateProduct = oProdService.SaveProduct(oCatalog);
                if (!string.IsNullOrEmpty(updateProduct))
                {
                    this.Message = MessageBox.DisplayErrorMessage(updateProduct);
                    return;
                }
                var sq = new SecureQueryString();
                sq["ProdId"] = oCatalog.Id;

                Response.Redirect("new3.aspx?q=" + sq);

            }

        }

        //protected void btnUpload_Click(object sender, EventArgs e)
        //{
        //    if (Path.GetExtension(fileUpload.PostedFile.FileName) == ".gif" || Path.GetExtension(fileUpload.PostedFile.FileName) == ".jpg" || Path.GetExtension(fileUpload.PostedFile.FileName) == ".jpeg" || Path.GetExtension(fileUpload.PostedFile.FileName) == ".png")
        //    {
        //        string sGuid = Guid.NewGuid().ToString();
        //        Company oComp = oCompService.GetCompanyByID(sCompanyID);
        //        if (String.IsNullOrEmpty(oComp.IsGoldMember.ToString()) || (bool)oComp.IsGoldMember == false)
        //        {
        //            if (oProd.CompanyProductImages.Count > 0)
        //            {
        //                this.Message = MessageBox.DisplayErrorMessage(Resources.Language.NotAllowedUploadImages);
        //            }
        //            else
        //            {
        //                HttpPostedFile jpeg_image_upload = fileUpload.PostedFile;
        //                string extension = Path.GetExtension(jpeg_image_upload.FileName);
        //                long FileSize = jpeg_image_upload.InputStream.Length;
        //                try
        //                {
        //                    oProdService.UploadProductImages(sCompanyID, sProdID, sGuid + extension, jpeg_image_upload.InputStream, true);
        //                }
        //                catch (Exception ex)
        //                {
        //                    this.Message = MessageBox.DisplayErrorMessage(ex.Message);
        //                }

        //            }
        //        }
        //        else
        //        {
        //            if ((bool)oComp.IsGoldMember)
        //            {
        //                HttpPostedFile jpeg_image_upload = fileUpload.PostedFile;
        //                string extension = Path.GetExtension(jpeg_image_upload.FileName);
        //                long FileSize = jpeg_image_upload.InputStream.Length;
        //                if (oProd.CompanyProductImages.Count() == 0)
        //                {
        //                    try
        //                    {
        //                        oProdService.UploadProductImages(sCompanyID, sProdID, sGuid + extension, jpeg_image_upload.InputStream, true);
        //                    }
        //                    catch (Exception ex)
        //                    {
        //                        this.Message = MessageBox.DisplayErrorMessage(ex.Message);
        //                    }
        //                }
        //                else
        //                {
        //                    try
        //                    {
        //                        oProdService.UploadProductImages(sCompanyID, sProdID, sGuid + extension, jpeg_image_upload.InputStream, false);
        //                    }
        //                    catch (Exception ex)
        //                    {
        //                        this.Message = MessageBox.DisplayErrorMessage(ex.Message);
        //                    }
        //                }
        //            }

        //        }
        //        if (oProd.StatusID == 1)
        //        {
        //            oProd.StatusID = EnumStatus.Pending.GetHashCode();
        //            oContext.SaveChanges();
        //        }
        //        BindPictures();
        //    }
        //    else
        //    {
        //        this.Message = MessageBox.DisplayErrorMessage(Resources.Language.UploadGif);
        //    }
        //}

        protected void btnReload_Click(object sender, EventArgs e)
        {
            BindPictures();
        }

    }
}